using System.Web.Mvc;
using ExtendedMvc.Ajax;
using ExtendedMvc.Html;

namespace ExtendedMvc.Elements {
	public class SubmitImage<TModel> : ImageBase<SubmitImage<TModel>> where TModel : class {
		private bool _skipValidation;
		private string _formId;
		private bool _disabled;
		private string _disabledSource;
		private IModelViewHelper<TModel> _helper;

		public SubmitImage(IModelViewHelper<TModel> helper, string source, string formId)
			: base(source, null) {
			SetAttribute(HtmlAttribute.Type, "submit");
			_helper = helper;
			_formId = formId;
		}

		public virtual SubmitImage<TModel> SkipValidation(bool value = true) {
			_skipValidation = value;
			return this;
		}

		public virtual SubmitImage<TModel> Disabled(bool value = true) {
			_disabled = value;
			return this;
		}

		public virtual SubmitImage<TModel> DisabledImage(string disabledSource = null) {
			_disabledSource = disabledSource;
			return this;
		}

		protected override void Prepare() {
			OnClick(_disabled ? "javascript: return false;" : string.Format(_skipValidation ? JavaScriptHelper.Submit : JavaScriptHelper.SubmitWithValidation, _formId));
			if (_disabled) {
				SetAttribute(HtmlAttribute.Disabled, HtmlAttribute.Disabled);
				if (_disabledSource != null) Source(_disabledSource);
			}
			Source(UrlHelper.GenerateContentUrl(source, _helper.ViewContext.HttpContext));
			base.Prepare();
		}
	}
}